package com.yan.shiro;

import com.yan.system.bean.User;
import com.yan.system.mapper.UserMapper;
import com.yan.system.service.MenuService;
import com.yan.utils.ApplicationHolder;
import com.yan.utils.ShiroUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class UserRealmConfig extends AuthorizingRealm {
///*	@Autowired
//    UserDao userMapper;
//	@Autowired
//	MenuService menuService;*/


    /**
     * 授权
     *
     *
     * SELECT DISTINCT
     m.perms
     FROM
     sys_menu m
     LEFT JOIN sys_role_menu rm ON m.menu_id = rm.menu_id
     LEFT JOIN sys_user_role ur ON rm.role_id = ur.role_id
     WHERE
     ur.user_id = 1;

     *
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        Long userId = ShiroUtils.getUserId();
        MenuService menuService = ApplicationHolder.getBean(MenuService.class);
        Set<String> perms = menuService.listPerms(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }


    /**
     * http://412887952-qq-com.iteye.com/blog/2299777
     * 认证信息.(身份验证)
     * :
     * Authentication 是用来验证用户身份
     * doGetAuthenticationInfo主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Map<String, Object> map = new HashMap<>(16);
        map.put("username", username);
        String password = new String((char[]) token.getCredentials());

        UserMapper userMapper = ApplicationHolder.getBean(UserMapper.class);
        // 查询用户信息
        User user = userMapper.list(map).get(0);

        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        // 密码错误
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        // 账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }

}
